// +----------------------------------------------------------------------
// | Manong.Cloud [ 领酷码农云 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.manong.cloud All rights reserved.
// +----------------------------------------------------------------------
// | Author: 稻草人 <qinuoyun@qq.com>
// +----------------------------------------------------------------------
// | Member: 围棋 飘逸者 Loumt Silence24
// +----------------------------------------------------------------------
import vm from 'vm';
import Module from './module';

/**
 * 轻代码
 */
class lightcode {

  /**
   * 搜索模型
   * @param str
   * @returns {*[]}
   */
  static queryMondel(str) {
    let reg = /M\((.*?)\)/g;
    let res = str.match(reg);
    let modeList = [];
    while (res = reg.exec(str)) {
      let s = res[1].replace(/\"/g, "")
      s = s.replace(/\'/g, "")
      modeList.push(s);
    }
    let newArr = [...new Set(modeList)];
    return newArr;
  }

  static compileCode(code) {
    let rule = /M\((.*?)\)/g;
    code = code.replace(rule, "await M($1)");
    //查找替换 添加异步方法
    let runtime = `
    async function run() {
      ${code}
    }
    run();
    `
    return runtime;
  }

  /**
   * 获取字段类型
   */
  static getFieldType(value, number) {
    switch (value) {
      case 'varchar':
      case 'int':
      case 1:
        return `${value}(${number})`;
        break;
      case 'text':
      case 'longtext':
      case 'datetime':
        return value
        break;
      default:
        return `${value}(${number})`;
    }
  }

  static getModel(name, prefix, APPID) {
    return new Module(name, {
      prefix: prefix,
      APPID: APPID
    });
  }

  dd() {
    function sync(fun) {
      (new Promise(function (resolve) {
        let row = fun();
        resolve(dddd)
      }))
    }
  }

  /**
   * 启动
   * @returns {any}
   */
  static bootstrap(code, common) {
    code = lightcode.compileCode(code);
    common = Object.assign({
      toJson: to_json,
      toArray: to_array,
      isString: is_string,
      isNull: is_null
    }, common)
    //设置内容
    vm.createContext(common);
    // 在执行上下文运行
    return vm.runInContext(code, common);
  }
}


export default lightcode;
